package city.spring.modules.medicalstation.drugwarehouseShelfExt.controller;

import city.spring.modules.medicalstation.drug.entity.DrugEntity;
import city.spring.modules.medicalstation.drug.repository.DrugRepository;
import city.spring.modules.medicalstation.drug.service.DrugService;
import city.spring.modules.medicalstation.drugwarehouse.entity.DrugwarehouseEntity;
import city.spring.modules.medicalstation.drugwarehouse.service.DrugwarehouseService;
import city.spring.modules.medicalstation.drugwarehouseShelfExt.entity.DrugwarehouseShelfExtEntity;
import city.spring.modules.medicalstation.drugwarehouseShelfExt.repository.DrugwarehouseShelfExtRepository;
import city.spring.modules.medicalstation.drugwarehouseShelfExt.service.DrugwarehouseShelfExtService;
import city.spring.modules.medicalstation.drugwarehouseShelfExt.vo.DrugwarehouseShelflevelVO;
import city.spring.modules.medicine.entity.MedicineEntity;
import city.spring.modules.medicine.service.MedicineService;
import city.spring.modules.system.entity.UserEntity;
import city.spring.modules.system.service.UserService;
import city.spring.utils.MyBatisUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static city.spring.utils.UserUtils.getPrincipal;

/**
 * Controller：医护站药品入库与货架关联表
 *
 * @author 谢金婷
 * @date 2020-09-24 16:34:05
 */
@RestController
@RequestMapping("/drugwarehouse/{warehousingId}/shelflevel")
public class DrugwarehouseShelfExtController extends ApiController {
    private final DrugwarehouseShelfExtService drugwarehouseShelfExtService;
    private final DrugwarehouseShelfExtRepository drugwarehouseShelfExtRepository;
    private final DrugwarehouseService drugwarehouseService;
    private final DrugService drugService;
    private final MedicineService medicineService;
    private final UserService userService;
    private final DrugRepository drugRepository;
    /**
     * 实体类可排序字段
     */
    private final List<SFunction<DrugwarehouseShelfExtEntity, ?>> entityOrderFields;

    public DrugwarehouseShelfExtController(DrugwarehouseShelfExtService drugwarehouseShelfExtService, DrugwarehouseShelfExtRepository drugwarehouseShelfExtRepository, DrugwarehouseService drugwarehouseService, DrugService drugService, MedicineService medicineService, UserService userService, DrugRepository drugRepository) {
        this.drugwarehouseShelfExtService = drugwarehouseShelfExtService;
        this.drugwarehouseShelfExtRepository = drugwarehouseShelfExtRepository;
        this.drugwarehouseService = drugwarehouseService;
        this.drugService = drugService;
        this.medicineService = medicineService;
        this.userService = userService;
        this.drugRepository = drugRepository;
        entityOrderFields = new ArrayList<>();
        entityOrderFields.add(DrugwarehouseShelfExtEntity::getId);
        entityOrderFields.add(DrugwarehouseShelfExtEntity::getDrugwarehousingId);
        entityOrderFields.add(DrugwarehouseShelfExtEntity::getShelflevelId);
        entityOrderFields.add(DrugwarehouseShelfExtEntity::getWarehousingquantity);
        entityOrderFields.add(DrugwarehouseShelfExtEntity::getTotal);
    }

    @ModelAttribute
    public void getWarehousingId(@PathVariable Integer warehousingId) {
        if (warehousingId == null) {
            throw new RuntimeException("入库单ID必须不为空");
        }
        System.out.println("warehousingId" + warehousingId);
    }

    /**
     * 获取全部的 <strong>医护站药品入库与货架关联表</strong> 列表
     */
    @GetMapping("all")
    public Object listAll(@PageableDefault Pageable pageable, DrugwarehouseShelfExtEntity entity) {
        LambdaQueryChainWrapper<DrugwarehouseShelfExtEntity> lambdaQuery = buildLambdaQuery(entity);
        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
        return success(lambdaQuery.list());
    }

    /**
     * 分页获取 <strong>医护站药品入库与货架关联表</strong> 列表
     *
     * @param pageable 分页参数信息
     */
//    @GetMapping
//    public Object list(@PageableDefault Pageable pageable, DrugwarehouseShelfExtEntity entity) {
//        LambdaQueryChainWrapper<DrugwarehouseShelfExtEntity> lambdaQuery = buildLambdaQuery(entity);
//        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
//        Page<DrugwarehouseShelfExtEntity> page = lambdaQuery.page(MyBatisUtils.toPage(pageable, false));
//        return success(page);
//    }

    /**
     * 获取物资出库所有货架列表
     *
     * @param warehousingId
     * @return
     */
    @GetMapping
    public Object list(@PathVariable Integer warehousingId) {
        return success(drugwarehouseShelfExtRepository.getWarehousingShelflevels(warehousingId));
    }

    /**
     * 获取一个 <strong>医护站药品入库与货架关联表</strong>
     *
     * @param id 主键ID
     */
//    @GetMapping("{id}")
//    public Object info(@PathVariable String id) {
//        return success(drugwarehouseShelfExtService.getById(id));
//    }

    /**
     * @param warehousingId
     * @param extId
     * @return
     */
    @GetMapping("{extId}")
    public Object getInfo(@PathVariable Integer warehousingId, @PathVariable String extId) {
        return success(drugwarehouseShelfExtRepository.getWarehousingShelflevel(warehousingId, extId));
    }


    //    /**
//     * 添加一个 <strong>医护站药品入库与货架关联表</strong>
//     *
//     * @param entity 修改后的信息
//     */
//    @PostMapping
//    public Object add(@RequestBody DrugwarehouseShelfExtEntity entity) {
//        drugwarehouseShelfExtService.saveDrugwarehouseShelfExt(entity);
//
//        HttpHeaders headers = new HttpHeaders();
//        headers.add(HttpHeaders.LOCATION, String.valueOf(entity.getId()));
//        return new ResponseEntity<>(headers, HttpStatus.CREATED);
//    }
    @PostMapping
    public Object addAll(@PathVariable Integer warehousingId, @RequestBody List<DrugwarehouseShelfExtEntity> shelflevels) {
        shelflevels.forEach(item -> item.setDrugwarehousingId(warehousingId));
        // 查出已有的数据
        List<DrugwarehouseShelflevelVO> dbShelflevels = drugwarehouseShelfExtRepository.getWarehousingShelflevels(warehousingId);

        // 数据库已经存在的物资列表
        Set<String> dbShelflevelIdsSet = dbShelflevels.stream()
                .map(DrugwarehouseShelfExtEntity::getShelflevelId)
                .collect(Collectors.toSet());
        // 过滤掉已经存在数据库的数据
        List<DrugwarehouseShelfExtEntity> needSaveShelflevels = shelflevels.stream()
                .filter(item -> {
                    item.setDrugwarehousingId(warehousingId);
                    String shelflevelId = item.getShelflevelId();
                    // 过滤出不存在数据库中的数据
                    return shelflevelId != null && !dbShelflevelIdsSet.contains(shelflevelId);
                }).collect(Collectors.toList());

        System.out.println("needSavemedicines" + needSaveShelflevels);
        BigDecimal totalquantity = new BigDecimal(0);
        for (DrugwarehouseShelfExtEntity ms : needSaveShelflevels) {
            totalquantity = totalquantity.add(ms.getWarehousingquantity());
        }
        System.out.println("totalquantity:" + totalquantity);
        // 入库单入库数量
        DrugwarehouseEntity drugwarehouseEntity = drugwarehouseService.getById(warehousingId);
        if (!needSaveShelflevels.isEmpty() && totalquantity.compareTo(drugwarehouseEntity.getQuantitySpecifications()) == 0) {
            drugwarehouseShelfExtService.saveBatch(needSaveShelflevels);

            List<DrugwarehouseShelfExtEntity> warehousingShelflevels = drugwarehouseShelfExtRepository.getWarehousingSls(warehousingId);
            for (DrugwarehouseShelfExtEntity shelfExtEntity : warehousingShelflevels) {
                System.out.println("m234" + shelfExtEntity);
                // 根据入库单id获取入库信息
                DrugwarehouseEntity drugwarehouseEntity1 = drugwarehouseService.getById(shelfExtEntity.getDrugwarehousingId());
                System.out.println("drugwarehouseEntity11234567" + drugwarehouseEntity1);

                //计算总价
                BigDecimal unitprice = drugwarehouseEntity1.getUnitprice() == null ? BigDecimal.ZERO : drugwarehouseEntity1.getUnitprice();
                System.out.println("总价 unitprice" + unitprice);
                BigDecimal quantity = shelfExtEntity.getWarehousingquantity() == null ? BigDecimal.ZERO : shelfExtEntity.getWarehousingquantity();
                System.out.println("总价 quantity" + quantity);
                shelfExtEntity.setTotal(quantity.multiply(unitprice));
                System.out.println("shelfExtEntity.getTotal()" + shelfExtEntity.getTotal());
                drugwarehouseShelfExtService.updateDrugwarehouseShelfExt(shelfExtEntity);

                // 1.如果药品信息中没有该药品编码，则新增药品信息，否则查找到该入库货架是否有该药品，有则更新库存，没有则新增药品信息
                //根据物资id查找物资信息
                if (drugwarehouseEntity.getWarehousingmethod().equals("本人缴存") || drugwarehouseEntity.getWarehousingmethod().equals("家属缴存")) {
                    DrugEntity drugEntity2 = drugService.getById(drugwarehouseEntity1.getMedicineId());
                    DrugEntity drugEntity1 = drugRepository.drugByShelfIdAndCode(shelfExtEntity.getShelflevelId(), drugEntity2.getCode());
                    if (drugEntity1 == null) {
                        DrugEntity drugEntity = new DrugEntity();
                        drugEntity.setCode(drugEntity2.getCode());
                        drugEntity.setName(drugEntity2.getName());
                        drugEntity.setCategory(drugEntity2.getCategory());
                        drugEntity.setSpecifications(drugEntity2.getSpecifications());
                        drugEntity.setUnit(drugEntity2.getUnit());
                        drugEntity.setUnitprice(drugEntity2.getUnitprice());
                        drugEntity.setDosageunit(drugEntity2.getDosageunit());
                        drugEntity.setSupplierId(drugEntity2.getSupplierId());
                        drugEntity.setManufacturer(drugEntity2.getManufacturer());
                        drugEntity.setType(drugEntity2.getType());
                        drugEntity.setStorehouseId(String.valueOf(drugwarehouseEntity1.getStorehouseId()));
                        drugEntity.setProductiondate(drugEntity2.getProductiondate());
                        drugEntity.setExpirationdate(drugEntity2.getExpirationdate());
                        drugEntity.setIswarehouse(1);
                        drugEntity.setShelfId(shelfExtEntity.getShelflevelId());
                        drugEntity.setWarehousingquantity(shelfExtEntity.getWarehousingquantity());
                        drugEntity.setQuantity(shelfExtEntity.getWarehousingquantity());
                        drugService.save(drugEntity);
                        HttpHeaders headers = new HttpHeaders();
                        headers.add(HttpHeaders.LOCATION, String.valueOf(drugEntity.getId()));
                    } else {
                        System.out.println("drugEntity1.getShelfId()" + drugEntity1.getShelfId());
                        if (drugEntity1.getShelfId().equals(shelfExtEntity.getShelflevelId())) {
                            System.out.println("第二种情况");
                            //更新入库数量=原来的入库数量+现在的入库数量
                            BigDecimal mwarehousingquantity = drugEntity1.getWarehousingquantity() == null ? BigDecimal.ZERO : drugEntity1.getWarehousingquantity();
                            drugEntity1.setWarehousingquantity(mwarehousingquantity.add(shelfExtEntity.getWarehousingquantity()));
                            System.out.println(mwarehousingquantity + "====" + shelfExtEntity.getWarehousingquantity());
                            // 更新库存=原来的库存+现在的入库数量
                            BigDecimal mquantity = drugEntity1.getQuantity() == null ? BigDecimal.ZERO : drugEntity1.getQuantity();
                            drugEntity1.setQuantity(mquantity.add(shelfExtEntity.getWarehousingquantity()));

                            drugService.lambdaUpdate()
                                    .set(DrugEntity::getWarehousingquantity, drugEntity1.getWarehousingquantity())
                                    .set(DrugEntity::getQuantity, drugEntity1.getQuantity())
                                    .eq(DrugEntity::getId, drugEntity1.getId())
                                    .update();
                        }
                    }
                } else {
                    MedicineEntity medicineEntity = medicineService.getById(drugwarehouseEntity1.getMedicineId());
                    DrugEntity drugEntity1 = drugRepository.drugByShelfIdAndCode(shelfExtEntity.getShelflevelId(), medicineEntity.getCode());
                    if (drugEntity1 == null) {
                        DrugEntity drugEntity = new DrugEntity();
                        drugEntity.setCode(medicineEntity.getCode());
                        drugEntity.setName(medicineEntity.getName());
                        drugEntity.setCategory(medicineEntity.getCategory());
                        drugEntity.setSpecifications(medicineEntity.getSpecifications());
                        drugEntity.setUnit(medicineEntity.getUnit());
                        drugEntity.setUnitprice(medicineEntity.getUnitprice());
                        drugEntity.setDosageunit(medicineEntity.getDosageunit());
                        drugEntity.setSupplierId(medicineEntity.getSupplierId());
                        drugEntity.setType(medicineEntity.getType());
                        drugEntity.setStorehouseId(String.valueOf(drugwarehouseEntity1.getStorehouseId()));
                        drugEntity.setProductiondate(medicineEntity.getProductiondate());
                        drugEntity.setExpirationdate(medicineEntity.getExpirationdate());
                        drugEntity.setIswarehouse(1);
                        drugEntity.setShelfId(shelfExtEntity.getShelflevelId());
                        drugEntity.setWarehousingquantity(shelfExtEntity.getWarehousingquantity());
                        drugEntity.setQuantity(shelfExtEntity.getWarehousingquantity());
                        drugService.save(drugEntity);
                        HttpHeaders headers = new HttpHeaders();
                        headers.add(HttpHeaders.LOCATION, String.valueOf(drugEntity.getId()));
                    } else {
                        System.out.println("drugEntity1.getShelfId()" + drugEntity1.getShelfId());
                        if (drugEntity1.getShelfId().equals(shelfExtEntity.getShelflevelId())) {
                            System.out.println("第二种情况");
                            //更新入库数量=原来的入库数量+现在的入库数量
                            BigDecimal mwarehousingquantity = drugEntity1.getWarehousingquantity() == null ? BigDecimal.ZERO : drugEntity1.getWarehousingquantity();
                            drugEntity1.setWarehousingquantity(mwarehousingquantity.add(shelfExtEntity.getWarehousingquantity()));
                            System.out.println(mwarehousingquantity + "====" + shelfExtEntity.getWarehousingquantity());
                            // 更新库存=原来的库存+现在的入库数量
                            BigDecimal mquantity = drugEntity1.getQuantity() == null ? BigDecimal.ZERO : drugEntity1.getQuantity();
                            drugEntity1.setQuantity(mquantity.add(shelfExtEntity.getWarehousingquantity()));

                            drugService.lambdaUpdate()
                                    .set(DrugEntity::getWarehousingquantity, drugEntity1.getWarehousingquantity())
                                    .set(DrugEntity::getQuantity, drugEntity1.getQuantity())
                                    .eq(DrugEntity::getId, drugEntity1.getId())
                                    .update();
                        }
                    }
                }
            }
            // 入库人
            // 当前登录用户
            UserEntity userEntity = userService.getUserByIdOrAccount(getPrincipal().getName());
            drugwarehouseEntity.setUsersId(userEntity.getId());
            drugwarehouseEntity.setIswarehouse(1);
            drugwarehouseEntity.setWarehousingdate(new Date());
            drugwarehouseService.lambdaUpdate()
                    .set(DrugwarehouseEntity::getUsersId, drugwarehouseEntity.getUsersId())
                    .set(DrugwarehouseEntity::getIswarehouse, drugwarehouseEntity.getIswarehouse())
                    .set(DrugwarehouseEntity::getWarehousingdate, drugwarehouseEntity.getWarehousingdate())
                    .eq(DrugwarehouseEntity::getId, drugwarehouseEntity.getId())
                    .update();


            /**
             * 出库后更新机构站药品库存
             */
            // 如果入库方式不是本人缴存或者家属缴存 也就是入库为机构养老领用申请的入库 则减少机构养老药品库存
//            if (!drugwarehouseEntity.getWarehousingmethod().equals("本人缴存")) {
//                if (!drugwarehouseEntity.getWarehousingmethod().equals("家属缴存")) {
//                    DrugwarehouseEntity drugwarehouseEntity1 = drugwarehouseService.getById(warehousingId);
//                    System.out.println("drugwarehouseEntity1" + drugwarehouseEntity1);
//                    MedicineEntity medicineEntity = medicineService.getById(drugwarehouseEntity1.getMedicineId());
//                    //更新出库数量=原来的出库数量+现在的出库数量
//                    BigDecimal deliveryquantity = drugwarehouseEntity1.getQuantity() == null ? BigDecimal.ZERO : drugwarehouseEntity1.getQuantity();
//                    BigDecimal mdeliveryquantity = medicineEntity.getDeliveryquantity() == null ? BigDecimal.ZERO : medicineEntity.getDeliveryquantity();
//                    medicineEntity.setDeliveryquantity(mdeliveryquantity.add(deliveryquantity));
//                    System.out.println(mdeliveryquantity + "-----====----" + deliveryquantity);
//                    // 更新库存=原来的库存-现在的出库数量
//                    BigDecimal mquantity = medicineEntity.getQuantity() == null ? BigDecimal.ZERO : medicineEntity.getQuantity();
//                    medicineEntity.setQuantity(mquantity.subtract(deliveryquantity));
//                    System.out.println(mquantity + "-----=-----" + deliveryquantity);
//                    medicineService.updateMedicine(medicineEntity);
//
//                }
//            }
//        } else {
////            // 修改入库状态
//            drugwarehouseEntity.setIswarehouse(2);
//            drugwarehouseService.lambdaUpdate()
//                    .set(DrugwarehouseEntity::getIswarehouse, drugwarehouseEntity.getIswarehouse())
//                    .eq(DrugwarehouseEntity::getId, drugwarehouseEntity.getId())
//                    .update();
//            // 窗口提示
//            JOptionPane.showMessageDialog(null, "入库数量不等于入库单数量", "错误", JOptionPane.ERROR_MESSAGE);
        }

        return success(null);

    }

    //        /**
//         * 修改一个 <strong>医护站药品入库与货架关联表</strong>
//         *
//         * @param id     主键ID
//         * @param entity 修改后的信息
//         */
//    @PutMapping("{id}")
//    public Object update(@PathVariable String id, @RequestBody DrugwarehouseShelfExtEntity entity) {
//        entity.setId(id);
//        drugwarehouseShelfExtService.updateDrugwarehouseShelfExt(entity);
//        return new ResponseEntity<>(HttpStatus.OK);
//    }
    @PutMapping("{extId}")
    public Object update(@PathVariable Integer warehousingId, @PathVariable String extId, @RequestBody DrugwarehouseShelfExtEntity extEntity) {
        extEntity.setId(extId);
        System.out.println("extEntity.getId()" + extEntity.getId());
        extEntity.setDrugwarehousingId(warehousingId);
        drugwarehouseShelfExtService.updateDrugwarehouseShelfExt(extEntity);
        return success(null);

    }


    /**
     * 删除一个 <strong>医护站药品入库与货架关联表</strong>
     *
     * @param id 主键ID
     */
    @DeleteMapping("{id}")
    public Object delete(@PathVariable String id) {
        drugwarehouseShelfExtService.deleteDrugwarehouseShelfExt(id);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 删除多个 <strong>医护站药品入库与货架关联表</strong>
     *
     * @param ids 主键ID列表
     */
    @DeleteMapping
    public Object deleteIds(@RequestBody List<String> ids) {
        drugwarehouseShelfExtService.deleteDrugwarehouseShelfExt(ids);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private LambdaQueryChainWrapper<DrugwarehouseShelfExtEntity> buildLambdaQuery(DrugwarehouseShelfExtEntity entity) {
        LambdaQueryChainWrapper<DrugwarehouseShelfExtEntity> lambdaQuery = drugwarehouseShelfExtService.lambdaQuery();
        lambdaQuery.eq(StringUtils.isNotBlank(entity.getId()), DrugwarehouseShelfExtEntity::getId, entity.getId());
        lambdaQuery.eq(entity.getDrugwarehousingId() != null, DrugwarehouseShelfExtEntity::getDrugwarehousingId, entity.getDrugwarehousingId());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getShelflevelId()), DrugwarehouseShelfExtEntity::getShelflevelId, entity.getShelflevelId());
        lambdaQuery.eq(entity.getWarehousingquantity() != null, DrugwarehouseShelfExtEntity::getWarehousingquantity, entity.getWarehousingquantity());
        lambdaQuery.eq(entity.getTotal() != null, DrugwarehouseShelfExtEntity::getTotal, entity.getTotal());
        return lambdaQuery;
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private QueryWrapper<DrugwarehouseShelfExtEntity> buildQuery(DrugwarehouseShelfExtEntity entity) {
        QueryWrapper<DrugwarehouseShelfExtEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(entity.getId()), "id", entity.getId());
        wrapper.eq(entity.getDrugwarehousingId() != null, "drugwarehousing_id", entity.getDrugwarehousingId());
        wrapper.like(StringUtils.isNotBlank(entity.getShelflevelId()), "shelflevel_id", entity.getShelflevelId());
        wrapper.eq(entity.getWarehousingquantity() != null, "warehousingquantity", entity.getWarehousingquantity());
        wrapper.eq(entity.getTotal() != null, "total", entity.getTotal());
        return wrapper;
    }

}
